package com.jdjw.modules.thirdpost.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jdjw.common.ResponseResult;
import com.jdjw.modules.abuttingjoint.entity.DwdGcJbxxJiande;
import com.jdjw.modules.abuttingjoint.mapper.DwdGcJbxxJiandeMapper;
import com.jdjw.modules.thirdpost.param.*;
import com.jdjw.modules.thirdpost.result.ProjectCodtResult;
import com.jdjw.modules.thirdpost.result.ProjectContrantResult;
import com.jdjw.modules.thirdpost.result.ProjectResult;
import com.jdjw.modules.thirdpost.result.ProjectTenderResult;
import com.jdjw.utils.CommonUtil;
import com.jdjw.utils.ConstantUtil;
import com.jdjw.utils.DateUtil;
import com.jdjw.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 工程项目基本信息，工程合同，工程投标 推送数据
 */
@Service
@Slf4j
public class ProjectServiceImpl extends ServiceImpl<DwdGcJbxxJiandeMapper, DwdGcJbxxJiande>
        implements IService<DwdGcJbxxJiande> {

    @Autowired
    private static DwdGcJbxxJiandeMapper dwdGcJbxxJiandeMapper;

    @Autowired
    static ThirdPostExceptionServiceImpl thirdPostExceptionServiceImpl;

    @Resource
    public void setThirdPostExceptionServiceImpl(ThirdPostExceptionServiceImpl thirdPostExceptionServiceImpl) {
        ProjectServiceImpl.thirdPostExceptionServiceImpl = thirdPostExceptionServiceImpl;
    }

    @Resource
    public void setDwdGcJbxxJiandeMapper(DwdGcJbxxJiandeMapper dwdGcJbxxJiandeMapper) {
        ProjectServiceImpl.dwdGcJbxxJiandeMapper = dwdGcJbxxJiandeMapper;
    }

    /**
     * 工程基本信息发送数据
     */
    public static void doPostProject(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 1;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 1;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 1;
        }
        try {
            //查询
            List<ProjectResult> all = dwdGcJbxxJiandeMapper.getListAll(thirdPostInParm);
            if (all == null || all.size() < 1) {
                log.info("工程基础表数据库查询数据为0条");
                return;
            }
            if (all.size() > 3000) {
                Collection<Collection<ProjectResult>> fgList = CommonUtil.subCollection(all, 2900);
                for (Collection<ProjectResult> obj : fgList) {
                    sendData((List<ProjectResult>) obj, url);
                }
            } else {
                sendData(all, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 工程基本数据组装数据
     */
    private static void sendData(List<ProjectResult> all, String url) {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        for (ProjectResult a : all) {
            //组装数据
            ProjectParam param = new ProjectParam();
            BeanUtils.copyProperties(a, param);
            param.setBiz_id(a.getBizId());
            param.setDel_flag(a.getDelFlag());
            //补0至16位
            param.setCwhxzqh(CommonUtil.addZeroForNum(param.getCwhxzqh(), 16));
            param.setZj_type(a.getZjTypeFinal());
            //数据库没有值，随便传一个
            param.setGclb("1");
            //转化为json字符串
            //字段为null转为空字符串
            //String jsonStr = JSONObject.toJSONString(param, CommonUtil.filter);
            String jsonStr = JSONObject.toJSONString(param);
            //转化为json对象
            list.add(JSONObject.parseObject(jsonStr));
        }
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSL(url, list);
        System.out.println("结果："+jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("工程基础表推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "doPostProject", "工程基本数据",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD, new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("工程基础表推送失败", result);
            }
        } else {
            log.info("工程基础表推送失败", "第三方返回空");
        }
    }

    /**
     * 工程合同发送数据
     */
    public static void doPostProjectContract(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 3;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 3;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 3;
        }
        try {
            //查询
            List<ProjectContrantResult> all = dwdGcJbxxJiandeMapper.getContractListAll(thirdPostInParm);
            if (all == null || all.size() < 1) {
                log.info("项目合同表数据库查询数据为0条");
                return;
            }
            if (all.size() > 3000) {
                Collection<Collection<ProjectContrantResult>> fgList = CommonUtil.subCollection(all, 2900);
                for (Collection<ProjectContrantResult> obj : fgList) {
                    sendDataContract((List<ProjectContrantResult>) obj, url);
                }
            } else {
                sendDataContract(all, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 工程合同组装数据
     *
     * @param all
     * @param url
     */
    private static void sendDataContract(List<ProjectContrantResult> all, String url) {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        for (ProjectContrantResult a : all) {
            //组装数据
            //生成规则:乡镇首字母大写+村社首字母大写+“HT”+合同签订时间+4位随机数字
            //编号没写
            ProjectContrantParam param = new ProjectContrantParam();
            BeanUtils.copyProperties(a, param);
            param.setBiz_id(a.getBizId());
            param.setDel_flag(a.getDelFlag());
            param.setParent_id(a.getParentId());
            //补0至16位
            param.setCwhxzqh(CommonUtil.addZeroForNum(param.getCwhxzqh(), 16));
            //转化为json字符串
            String jsonStr = JSONObject.toJSONString(param);
            //转化为json对象
            list.add(JSONObject.parseObject(jsonStr));
        }
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSL(url, list);
        System.out.println("结果："+jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("工程合同表推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "doPostProjectContract", "工程合同表数据",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD, new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("工程合同表推送失败", result);
            }
        } else {
            log.info("工程合同表推送失败", "第三方返回空");
        }
    }


    /**
     * 工程合同发送数据
     */
    public static void doPostProjectTender(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 4;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 4;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 4;
        }
        try {
            //查询
            List<ProjectTenderResult> all = dwdGcJbxxJiandeMapper.getTendertListAll(thirdPostInParm);
            if (all == null || all.size() < 1) {
                log.info("项目合同表数据库查询数据为0条");
                return;
            }
            if (all.size() > 3000) {
                Collection<Collection<ProjectTenderResult>> fgList = CommonUtil.subCollection(all, 2900);
                for (Collection<ProjectTenderResult> obj : fgList) {
                    sendDataTender((List<ProjectTenderResult>) obj, url);
                }
            } else {
                sendDataTender(all, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 工程合同组装数据
     *
     * @param all
     * @param url
     */
    private static void sendDataTender(List<ProjectTenderResult> all, String url) {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        for (ProjectTenderResult a : all) {
            //组装数据
            ProjectTenderParam param = new ProjectTenderParam();
            BeanUtils.copyProperties(a, param);
            param.setBiz_id(a.getBizId());
            param.setDel_flag(a.getDelFlag());
            param.setParent_id(a.getParentId());
            //补0至16位
            param.setCwhxzqh(CommonUtil.addZeroForNum(param.getCwhxzqh(), 16));
            //转化为json字符串
            String jsonStr = JSONObject.toJSONString(param);
            //转化为json对象
            list.add(JSONObject.parseObject(jsonStr));
        }
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSL(url, list);
        System.out.println("结果："+jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("工程合同表推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "doPostProjectTender", "工程合同表数据",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD, new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("工程合同表推送失败", result);
            }
        } else {
            log.info("工程合同表推送失败", "第三方返回空");
        }
    }


    /**
     * 工程造价发送数据
     */
    public static void doPostProjectCost(ThirdPostInParm thirdPostInParm) {
        String url = "";
        //全量
        if (ConstantUtil.ALL_TYPE.equals(thirdPostInParm.getMethodType())) {
            url = ConstantUtil.ALL_THIRD_POST + 31;
        } else if (ConstantUtil.ADD_TYPE.equals(thirdPostInParm.getMethodType())) {
            //增量必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.ADD_THIRD_POST + 31;
        } else {
            //更新必须有时间
            if (StringUtils.isEmpty(thirdPostInParm.getStartTime()) &&
                    StringUtils.isEmpty(thirdPostInParm.getEndTime())) {
                return;
            }
            url = ConstantUtil.UPDATE_THIRD_POST + 31;
        }
        try {
            //查询
            List<ProjectCodtResult> all = dwdGcJbxxJiandeMapper.getCostListAll(thirdPostInParm);
            if (all == null || all.size() < 1) {
                log.info("项目合同表数据库查询数据为0条");
                return;
            }
            if (all.size() > 3000) {
                Collection<Collection<ProjectCodtResult>> fgList = CommonUtil.subCollection(all, 2900);
                for (Collection<ProjectCodtResult> obj : fgList) {
                    sendDataCost((List<ProjectCodtResult>) obj, url);
                }
            } else {
                sendDataCost(all, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 工程造价组装数据
     *
     * @param all
     * @param url
     */
    private static void sendDataCost(List<ProjectCodtResult> all, String url) {
        ResponseResult result = new ResponseResult();
        ArrayList list = new ArrayList();
        for (ProjectCodtResult a : all) {
            //组装数据
            ProjectCodtParam param = new ProjectCodtParam();
            BeanUtils.copyProperties(a, param);
            param.setBiz_id(a.getBizId());
            param.setDel_flag(a.getDelFlag());
            param.setParent_id(a.getParentId());
            //补0至16位
            param.setCwhxzqh(CommonUtil.addZeroForNum(param.getCwhxzqh(), 16));
            //bgnr 变更内容太长，对面接收不了
//            param.setBgnr(a.getBgnr());
            //转化为json字符串
            String jsonStr = JSONObject.toJSONString(param);
            //转化为json对象
            list.add(JSONObject.parseObject(jsonStr));
        }
        //发送(post)
        net.sf.json.JSONObject jsonObject = HttpRequestUtil.getHttpResponseJsonAllSSLTS(url, list);
        System.out.println("结果："+jsonObject);
        if (jsonObject != null) {
            if ("200".equals(jsonObject.get("code"))) {
                result.setCode(200);
                result.setMsg("SUCCESS");
                result.setData("推送完成");
                log.info("工程合同表推送成功"+list.size(), result);
            } else {
                //记录日志
                thirdPostExceptionServiceImpl.insertExceptionData(
                        "doPostProjectCost", "工程合同表数据",
                        jsonObject.getString("message"),
                        DateUtil.formatDate(DateUtil.FORMAT_YMD, new Date().getTime()));
                result.setCode(500);
                result.setMsg("ERROR");
                result.setData(jsonObject.getString("message"));
                log.info("工程合同表推送失败", result);
            }
        } else {
            log.info("工程合同表推送失败", "第三方返回空");
        }
    }
}
